package com.leetcode.string;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MinWindow {

    public static void main(String[] args) {

    }

    Map<Character, Integer> tCountMap = new HashMap<>();
    Map<Character, Integer> sCountMap = new HashMap<>();

    public String minWindow(String s, String t) {
        for (int i = 0; i < t.length(); i++) {
            char ch = t.charAt(i);
            tCountMap.put(ch, tCountMap.getOrDefault(ch, 0) + 1);
        }
        int left = 0;
        int right = -1;
        int sLen = s.length();
        int len = Integer.MAX_VALUE;
        int ansL = -1;
        int ansR = -1;
        while(right < sLen) {
            ++right;
            if (right < sLen && tCountMap.containsKey(s.charAt(right))) {
                sCountMap.put(s.charAt(right),
                        sCountMap.getOrDefault(s.charAt(right), 0) + 1);
            }
            while(check() && left <= right) {
                if (right - left + 1 < len) {
                    len = right - left + 1;
                    ansL = left;
                    ansR = left + len;
                }
                char lCh = s.charAt(left);
                if (tCountMap.containsKey(lCh)) {
                    sCountMap.put(lCh, sCountMap.getOrDefault(lCh, 0) -1);
                }
                left++;
            }
        }
        return ansL == -1 ? "" : s.substring(ansL, ansR);
    }

    private boolean check() {
        Iterator iterator = tCountMap.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry entry = (Map.Entry)iterator.next();
            Character key = (Character) entry.getKey();
            Integer val = (Integer) entry.getValue();
            if (sCountMap.getOrDefault(key, 0) < val) {
                return false;
            }
        }
        return  true;
    }
}
